package com.chen;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *文件下载
 *@author：email: <a href="cyb@ewppay.com"> Administrator </a> 
 *@Date 2017-2-6 下午3:19:16 
 */
//asyncSupported是否启用异步处理支持
@WebServlet(asyncSupported = false,urlPatterns = {"/servletDownload"})
public class ServletDownload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 13252352523L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String filename = req.getParameter("filename");
		System.out.println(filename+"=========");
		
		resp.setContentType("application/octet-stream");
		//resp.setContentType(getServletContext().getMimeType(filename));  此处会直接打开文件
		resp.addHeader("Content-Disposition", "attachment; filename=" + resp.encodeURL(filename));  
		String fullFileName = getServletContext().getRealPath("/download/" + filename);
		InputStream in = new FileInputStream(fullFileName);
		OutputStream out = resp.getOutputStream();
		
		int b;
		while((b=in.read()) != -1){
			out.write(b);
		}
		in.close();
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}

}
